package com.example.prom.qianduoduo.y2025.handler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.prom.qianduoduo.y2025.model.MoleculeTargetItem;
import com.example.prom.qianduoduo.y2025.model.MoleculeItem;
import com.example.prom.strategy.excel.CustomCellStyleStrategy;
import com.example.prom.strategy.excel.CustomColumnWidthStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Description
 *
 * @author DangWen
 */
public class TcmspDataMergeHandler {
    private static final Logger log = LoggerFactory.getLogger(TcmspDataMergeHandler.class);

    public static void main(String[] args) {
        // 从指定目录中读取所有 .xlsx 文件
        File folder = new File("D:\\dangwen\\钱多多\\");
        File[] filesArray = folder.listFiles((dir, name) -> name.endsWith(".xlsx"));
        List<String> files = new ArrayList<>();
        if (filesArray != null) {
            for (File file : filesArray) {
                files.add(file.getAbsolutePath());
            }
        }

        mergeExcelFiles(files, "D:\\dangwen\\钱多多\\mergedTargets.xlsx");
    }

    public static void mergeExcelFiles(List<String> sourceFiles, String targetFile) {

        // 用来收集所有文件的“两页”数据
        List<MoleculeItem> ingredients          = new ArrayList<>();
        List<MoleculeTargetItem> targetItems     = new ArrayList<>();

        // 1. 先全部读完
        for (String file : sourceFiles) {
            readOneFile(file, ingredients, targetItems);
        }
        log.info("Ingredients 共 {} 条数据, Related Targets 共 {} 条数据", ingredients.size(), targetItems.size());
        // 添加对targetItems的去重处理，基于targetName去重
        Map<String, MoleculeTargetItem> distinctMap = targetItems.stream()
                .collect(Collectors.toMap(MoleculeTargetItem::getTargetName, item -> item, (existing, replacement) -> existing));
        System.out.println("distinctList size: " + distinctMap.size());
        List<MoleculeTargetItem> distinctList = new ArrayList<>(distinctMap.values());
        log.info("Ingredients 共 {} 条数据, Related Targets 共 {} 条数据", ingredients.size(), distinctList.size());

        // 2. 写出到新文件
        try (ExcelWriter writer = EasyExcel.write(targetFile)
                .registerWriteHandler(new CustomColumnWidthStrategy())
                .registerWriteHandler(new CustomCellStyleStrategy())
                .build()) {

            WriteSheet ws1 = EasyExcel.writerSheet("Ingredients")
                    .head(MoleculeItem.class)
                    .build();
            WriteSheet ws2 = EasyExcel.writerSheet("Related Targets")
                    .head(MoleculeTargetItem.class)
                    .build();


            writer.write(ingredients, ws1);
            writer.write(distinctList,   ws2);
        }

        System.out.printf("合并完成，共 %d 条有效药品数据，%d 条无数据记录 → %s%n",
                ingredients.size(), targetItems.size(), targetFile);
    }

    private static void readOneFile(String file,
                                   List<MoleculeItem> medicineList,
                                   List<MoleculeTargetItem> noDataList) {

        // ---------- Sheet1：符合爬取条件 ----------
        EasyExcel.read(file, MoleculeItem.class,
                        new PageReadListener<MoleculeItem>(medicineList::addAll))
                .sheet("Ingredients")
                .doRead();

        // ---------- Sheet2：不符合爬取条件 ----------
        EasyExcel.read(file, MoleculeTargetItem.class,
                        new PageReadListener<MoleculeTargetItem>(noDataList::addAll))
                .sheet("Related Targets")
                .doRead();
    }
}
